<?php
namespace App\Api\Controllers\Cmbc;
require_once("demo/www/php_java.php");//引用LAJP提供的PHP脚本

use App\Models\YinkaStore;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
class BaseController
{
    static $instance, $data;



//    const MIAN = 'https://wxpay.cmbc.com.cn/mobilePlatform/appserver/lcbpPay.do';
//    const ORDER_QUERY = 'https://wxpay.cmbc.com.cn/mobilePlatform/appserver/paymentResultSelect.do';
//    const REFUND = 'https://wxpay.cmbc.com.cn/mobilePlatform/appserver/cancelTrans.do';


    const MIAN = 'https://epay.cmbc.com.cn/appweb/appserver/lcbpPay.do';
    const ORDER_QUERY = 'https://epay.cmbc.com.cn/appweb/appserver/paymentResultSelect.do';
    const REFUND = 'https://epay.cmbc.com.cn/appweb/appserver/cancelTrans.do';
//    const MIAN = 'http://wxpay.cmbc.com.cn:1080/mobilePlatform/appserver/lcbpPay.do';


    public static function getInstance ()
    {
        if (! isset(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function params ($data, $cert)
    {
        $sign = self::createSign([
            'data'    => json_encode($data),
            'prikey'  => $cert['base64P12Data'],
            'signalg' => $cert['base64P12SignAlg'],
            'p12pwd'  => $cert['P12Password']
        ]);
        $body = json_encode($data);

        self::$data['businessContext'] = self::createContext([
            'data' => json_encode(['sign' => $sign, 'body' => $body]),
            'prikey'  => $cert['base64CertData'],
            'signalg' => $cert['base64CertSignAlg'],
        ]);
        return $this;
    }

    public static function createContext1 ($data)
    {
        $rs = json_decode(lajp_call(
            "cfca.sadk.api.EnvelopeKit::envelopeMessage",
            $data['data'],
            $data['signalg'],
            $data['prikey']
        ), true);
        error_log(date('Y-m-d H:i:s')." 【createContext】： ".json_encode([$rs])."\n\n", 3, "/tmp/". 'cmbc'.date('Ymd').".log");

        if (isset($rs['Base64EnvelopeMessage'])) {
            return $rs['Base64EnvelopeMessage'];
        }
        return '';
    }

    public static function createSign1 ($data)
    {
        $rs = json_decode(lajp_call(
            "cfca.sadk.api.SignatureKit::P1SignMessage",
            $data['signalg'],
            $data['data'],
            $data['prikey'],
            $data['p12pwd']
        ), true);
        error_log(date('Y-m-d H:i:s')." 【createSign】： ".json_encode([$rs])."\n\n", 3, "/tmp/". 'cmbc'.date('Ymd').".log");

        if (isset($rs['Base64SignatureData'])) {
            return $rs['Base64SignatureData'];
        }
        return '';
    }
    public static function decryptContext1 ($response, $cert)
    {
        $rs = json_decode(lajp_call(
            "cfca.sadk.api.EnvelopeKit::openEvelopedMessage",
            $response,
            $cert['base64CertSignAlg'],
            $cert['base64P12Data'],
            $cert['P12Password']
        ), true);
        error_log(date('Y-m-d H:i:s')." 【decryptContext】： ".json_encode([$rs])."\n\n", 3, "/tmp/". 'cmbc'.date('Ymd').".log");
        if (isset($rs['Base64SourceString'])) {
            return base64_decode($rs['Base64SourceString']);
        }
        return '';
    }

    public static function createContext($data)
    {
        $curl = curl_init();
        $headers[] = 'Charset: UTF-8';
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_URL, 'http://cmbc.wftpay.cn/get_context_data.php');
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

        $tmpInfo = curl_exec($curl);     //返回api的json对象
        $a = curl_error($curl);
        if(!empty($a)){
            error_log(date('Y-m-d H:i:s')." 【民生签名error】： ".json_encode([$a])."\n\n", 3, "/tmp/". 'cmbc'.date('Ymd').".log");
        }
        curl_close($curl);
        error_log(date('Y-m-d H:i:s')." 【民生签名2】： ".json_encode([$data,$tmpInfo])."\n\n", 3, "/tmp/". 'cmbc'.date('Ymd').".log");

        $rs = json_decode($tmpInfo, true);
        if (isset($rs['Base64EnvelopeMessage'])) {
            return $rs['Base64EnvelopeMessage'];
        }
        return '';
    }

    public static function createSign($data)
    {
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, 'http://cmbc.wftpay.cn/get_sign_data.php');
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

        $tmpInfo = curl_exec($curl);     //返回api的json对象
        $a = curl_error($curl);
        if(!empty($a)){
            error_log(date('Y-m-d H:i:s')." 【民生签名error】： ".json_encode([$a])."\n\n", 3, "/tmp/". 'cmbc'.date('Ymd').".log");
        }
        curl_close($curl);
        error_log(date('Y-m-d H:i:s')." 【民生签名1】： ".json_encode([$data,$tmpInfo])."\n\n", 3, "/tmp/". 'cmbc'.date('Ymd').".log");
        //var_dump($tmpInfo);
        $rs = json_decode($tmpInfo, true);
        if (isset($rs['Base64SignatureData'])) {
            return $rs['Base64SignatureData'];
        }



        return '';
    }

    public static function decryptContext($response, $cert)
    {
        $curl = curl_init();
        $data = [
            'data'    => $response,
            'prikey'  => $cert['base64P12Data'],
            'signalg' => $cert['base64CertSignAlg'],
            'p12pwd'  => $cert['P12Password']
        ];
//        $data = [
//            'data'    => 'MIIDWAYKKoEcz1UGAQQCA6CCA0gwggNEAgECMYGdMIGaAgECgBSZ/3CNMPowKPYAVrnTjiQbtRIkqjANBgkqgRzPVQGCLQMFAARwT8z6R273MJdEXedMGOev8WmP347MDdZnbBdn2fWRMlIyiwlJjgU5H6tl30ENi7Ufj+oM+uGttJp/S9Aqc8GqfENy/aLwGvnGPoDnyuKc7lXqhvS+QNTv/Vw+iK7jhOyHdN1jSkJgqfpedRKBrucBzTCCAp0GCiqBHM9VBgEEAgEwGwYHKoEcz1UBaAQQPUygv50YOPBwHBKSzP+TWICCAnDzPJTmY7y2YVkQFaoVha7o1y98gHnbDvNA4k0EkGS7XU2gprMJlcxBQyQvM4CoIBs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DVQQGEwJDTjENMAsGA1UECgwEQ01CQzESMBAGA1UECwwJQ01CQ19EQ01TMRkwFwYDVQQLDBBPcmdhbml6YXRpb25hbC0xMSUwIwYDVQQDDBwwMzA1QFpKTkZIMDAxQOa1juWNl+WIhuihjEAxMFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEf9Rpyii9VJfQOx8Ls5p+WGQoKEv8TIE65DVX2PFobQ+qdBDfULfizXD5K7koV0Qr+eJ3ucWUb13Zx7nGNvyCCqOCAZEwggGNMB8GA1UdIwQYMBaAFOJ+thC7lOsV5q7RFQr/6NegVzmdMEgGA1UdIARBMD8wPQYIYIEchu8qAgIwMTAvBggrBgEFBQcCARYjaHR0cDovL3d3dy5jZmNhLmNvbS5jbi91cy91cy0xMy5odG0wgdQGA1UdHwSBzDCByTAvoC2gK4YpaHR0cDovLzIxMC43NC40Mi4zL09DQTIxL1NNMi9jcmwyMTA3My5jcmwwgZWggZKggY+GgYxsZGFwOi8vMjEwLjc0LjQyLjEwOjM4OS9DTj1jcmwyMTA3MyxPVT1TTTIsT1U9Q1JMLE89Q0ZDQSBTTTIgVEVTVCBPQ0EyMSxDPUNOP2NlcnRpZmljYXRlUmV2b2NhdGlvbkxpc3Q/YmFzZT9vYmplY3RjbGFzcz1jUkxEaXN0cmlidXRpb25Qb2ludDALBgNVHQ8EBAMCA/gwHQYDVR0OBBYEFJn/cI0w+jAo9gBWudOOJBu1EiSqMB0GA1UdJQQWMBQGCCsGAQUFBwMCBggrBgEFBQcDBDAMBggqgRzPVQGDdQUAA0gAMEUCIQCWgnQ3rMcX5B/FHKBQY5VRs3XTyzLhtuG4+vmEpI81egIgWTu6ftHjSeoH8ePpoA7J/+tXA+jMP7fgh8lP6gOODwQ=',
//            'signalg' => 'DESede/CBC/PKCS7Padding',
//            'p12pwd'  => '123abc'
//        ];
        curl_setopt($curl, CURLOPT_URL, 'http://cmbc.wftpay.cn/decrypt_context_data.php');
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

        $tmpInfo = curl_exec($curl);     //返回api的json对象
        $a = curl_error($curl);
        if(!empty($a)){
            error_log(date('Y-m-d H:i:s')." 【民生签名error】： ".json_encode([$a])."\n\n", 3, "/tmp/". 'cmbc'.date('Ymd').".log");
        }
        curl_close($curl);
        error_log(date('Y-m-d H:i:s')." 【民生解密】： ".json_encode([$data,$tmpInfo])."\n\n", 3, "/tmp/". 'cmbc'.date('Ymd').".log");

        $rs = json_decode($tmpInfo, true);

        if (isset($rs['Base64SourceString'])) {
            return base64_decode($rs['Base64SourceString']);
        }
        return '';
    }

    public function build ($cert, $url)
    {
// 初始化cURL会话
        $ch = curl_init();
// 设置cURL选项
        curl_setopt($ch, CURLOPT_URL, $url); // 要提交的URL
        curl_setopt($ch, CURLOPT_POST, true); // 设置为POST请求
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Charset: UTF-8'
        ));
//        echo json_encode(self::$data);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(self::$data)); // 表单数据
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 返回响应而不是输出

// 执行cURL会话
        $response = curl_exec($ch);

// 关闭cURL会话
        curl_close($ch);
        error_log(date('Y-m-d H:i:s')." 【民生build】： ".json_encode([self::$data, $response])."\n\n", 3, "/tmp/". 'cmbc'.date('Ymd').".log");

        $rs = json_decode($response, true);

        if (isset($rs['gateReturnType']) && $rs['gateReturnType'] == 'S') { //网关成功
            $decryptContext = json_decode(self::decryptContext($rs['businessContext'], $cert), true);
            $retData = [];
            if (isset($decryptContext['body'])) {
                $retData = json_decode($decryptContext['body'], true);
            }
            if (!empty($retData)) {
                return [
                    'status'  => 1,
                    'data'    => $retData,
                    'message' => ''
                ];
            } else {
                return [
                    'status'  => 2,
                    'data'    => $retData,
                    'message' => '数据异常'
                ];
            }
        } else {
            return [
                'status'  => 3,
                'message' => isset($rs['gateReturnMessage']) && !empty($rs['gateReturnMessage']) ? $rs['gateReturnMessage'] : '失败',
                'data' => ''
            ];
        }
    }




}